package com.cxy.instarsystem.service;

import com.cxy.instarsystem.dao.VideoRepository;
import com.cxy.instarsystem.po.VCategory;
import com.cxy.instarsystem.po.Video;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class VideoServiceImpl implements VideoService  {

    @Autowired
    private VideoRepository videoRepository;


    @Override
    public Page<Video> listVideos(Pageable pageable, String query, String cid) {
        return videoRepository.findAll(new Specification<Video>() {
            @Override
            public Predicate toPredicate(Root<Video> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (!"0".equals(cid)){
                    predicates.add(cb.equal(root.get("vCategory").get("id"),cid));
                }
                if(!"".equals(query)&&query!=null){
                    predicates.add(cb.like(root.get("title"),"%"+query+"%"));
//                    predicates.add(cb.like(root.get("info"),"%"+query+"%"));
                }
                cq.where(predicates.toArray(new Predicate[0]));
                return null;
            }
        },pageable);
    }


    @Override
    public Long getTotalNum() {
        return videoRepository.count();
    }



}
